const {
    DataTypes,
    Sequelize,
    Op
} = require('sequelize');

const {
    database, //数据库
    username, //用户名
    password, //密码
    host //服务器
} = require('../config');

const sequelize = new Sequelize(database, username, password, {
    host,
    dialect: 'mysql',
    logging: false,
    define: {
        //不需要事件戳
        timestamps: false,
        // 设置数据库定义的类型
        engine: 'MYISAM'
    },
});

const User = require('./model/user')(sequelize, DataTypes);
const Category = require('./model/category')(sequelize, DataTypes);
const Comment = require('./model/comment')(sequelize, DataTypes);
const Post = require('./model/post')(sequelize, DataTypes);
const Like = require('./model/like')(sequelize, DataTypes);
const Follow = require('./model/follow')(sequelize, DataTypes);
const Cover = require('./model/cover')(sequelize, DataTypes);

//数据表建立关系
// 用户- 喜爱内容 - 文章 1对多对1
User.hasMany(Like);
Like.belongsTo(User);
Post.hasMany(Like);
Like.belongsTo(Post);

// 分类与文章 多对多
Category.belongsToMany(Post, {
    through: 'post_category'
});
Post.belongsToMany(Category, {
    through: 'post_category'
});

// 用户与文章 1对多
User.hasMany(Post);
Post.belongsTo(User);

//文章与封面 1对多
Post.hasMany(Cover, {
    as: 'cover'
});
Cover.belongsTo(Post);

// 文章-评论-用户 1对多对1
User.hasMany(Comment);
Comment.belongsTo(User);
Post.hasMany(Comment);
Comment.belongsTo(Post);

// 用户 - 关注 - 用户 1对多对1
User.hasMany(Follow);
Follow.belongsTo(User);
User.hasMany(Follow, {
    as: 'followUser'
});
Follow.belongsTo(User, {
    as: 'followUser'
});


//模型输出
module.exports = {
    User,
    Category,
    Comment,
    Post,
    Like,
    Follow,
    Sequelize,
    sequelize,
    Op,
    Cover
}